package com.bsoft.gol.hcs.common.dao;


import com.bsoft.gol.hcs.clinical.bean.qo.DepartmentListQo;
import com.bsoft.gol.hcs.clinical.bean.qo.DoctorListQo;
import com.bsoft.gol.hcs.clinical.bean.vo.DepartmentListVo;
import com.bsoft.gol.hcs.clinical.bean.vo.DoctorListVo;
import com.bsoft.gol.hcs.common.entity.SysParameter;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public abstract class SysParameterDAO extends HibernateSupportDelegateDAO<SysParameter> {


    @DAOMethod(sql = " from SysParameter where fusMedicalRecordsId =:fusMedicalRecordsId ")
    public abstract void updateSysParameterByKey(@DAOParam("parameterKey") String parameterKey,
                                                 @DAOParam("nowTime") String nowTime);

    @DAOMethod(sql = " from SysParameter where parameterKey =:parameterKey and parameterStartLoading = 1 ")
    public abstract List<SysParameter> querySysParameter(@DAOParam("parameterKey") String parameterKey);

    @DAOMethod(sql = " from SysParameter where parameterKey =:parameterKey ")
    public abstract SysParameter getSysParameter(@DAOParam("parameterKey") String parameterKey);


    public List<DepartmentListVo> queryDepartmentList(final DepartmentListQo departmentListQo) {
        HibernateStatelessResultAction<List<DepartmentListVo>> action = new AbstractHibernateStatelessResultAction<List<DepartmentListVo>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getDepartmentListStringBuffer(departmentListQo);
                Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                sqlQuery.setParameter("orgId", departmentListQo.getOrganizationId());
                if (StringUtils.isNotEmpty(departmentListQo.getDepartmentId())) {//科室ID
                    sqlQuery.setParameter("deptId", departmentListQo.getDepartmentId());
                }
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                setResult(mapDeptToList(dbList));
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private StringBuffer getDepartmentListStringBuffer(final DepartmentListQo departmentListQo) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT   id,  CODE departmentId,  TITLE departmentName,  INTRO departmentInformation FROM  app_department WHERE ORGCODE =:orgId");
        if (StringUtils.isEmpty(departmentListQo.getDepartmentId())) {
            stringBuffer.append(" AND PCODE = 0 ");
        } else {
            stringBuffer.append(" AND CODE = :deptId ");
        }
        return stringBuffer;
    }

    private List<DepartmentListVo> mapDeptToList(final List<Map> maps) {
        List<DepartmentListVo> docTeamListRespList = new ArrayList<>();
        for (Map map : maps) {
            docTeamListRespList.add(ConversionUtils.convert(map, DepartmentListVo.class));
        }
        return docTeamListRespList;
    }

    public List<DepartmentListVo.DepartmentListBean> querySunDepartmentList(final String orgId, final List<String> deptIdList) {
        HibernateStatelessResultAction<List<DepartmentListVo.DepartmentListBean>> action = new AbstractHibernateStatelessResultAction<List<DepartmentListVo.DepartmentListBean>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getSunDepartmentListStringBuffer(deptIdList);
                Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                sqlQuery.setParameter("orgId", orgId);
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                setResult(mapSunDeptToList(dbList));
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private StringBuffer getSunDepartmentListStringBuffer(final List<String> deptIdList) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("  SELECT  id, PCODE pCode,  CODE departmentId, TITLE departmentName, address address, TEL telephone FROM  app_department \n" +
                "WHERE ORGCODE =:orgId AND PCODE in ( ");
        if (deptIdList.size() > 0) {
            for (int i = 0; i < deptIdList.size(); i++) {
                stringBuffer.append("'");
                stringBuffer.append(deptIdList.get(i));
                stringBuffer.append("'");
                if (i < deptIdList.size() - 1) {
                    stringBuffer.append(",");
                }
            }
        } else {
            stringBuffer.append("'0'");
        }
        stringBuffer.append(")");
        return stringBuffer;
    }

    private List<DepartmentListVo.DepartmentListBean> mapSunDeptToList(final List<Map> maps) {
        List<DepartmentListVo.DepartmentListBean> docTeamListRespList = new ArrayList<>();
        for (Map map : maps) {
            docTeamListRespList.add(ConversionUtils.convert(map, DepartmentListVo.DepartmentListBean.class));
        }
        return docTeamListRespList;
    }

    public List<DoctorListVo> queryDoctorList(final DoctorListQo doctorListQo) {
        HibernateStatelessResultAction<List<DoctorListVo>> action = new AbstractHibernateStatelessResultAction<List<DoctorListVo>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getDoctorListStringBuffer(doctorListQo);
                Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
                sqlQuery.setParameter("orgId", doctorListQo.getOrganizationId());
                if (StringUtils.isNotEmpty(doctorListQo.getDepartmentId())) {
                    sqlQuery.setParameter("deptCode", doctorListQo.getDepartmentId());
                }
                if (StringUtils.isNotEmpty(doctorListQo.getDoctorId())) {//科室ID
                    sqlQuery.setParameter("doctorId", doctorListQo.getDoctorId());
                }
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                setResult(mapDocToList(dbList));
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private StringBuffer getDoctorListStringBuffer(final DoctorListQo doctorListQo) {
        StringBuffer stringBuffer = new StringBuffer();
        switch (doctorListQo.getQueryType()) {
            case 1://根据行政科室查
                stringBuffer.append("SELECT  t.`ORGCODE` organizationId,  t.`ORGNAME` organizationName,t.`CODE` departmentId,t.`TITLE` departmentName," +
                        "  d.`CODE` doctorId,d.`ID` docId,d.prac_type doctorJob,d.NAME doctorName,d.INTRODUCE doctorResume,d.SEXCODE doctorSex,d.EXPERT doctorGoodAt," +
                        " d.doctor_title professionalCode,d.mobile telephone,d.PROFESSIONALTITLE professionalName FROM app_doctor d LEFT JOIN `app_department` t ON t.`ID` = d.`administration_dept_id` " +
                        "WHERE t.`ORGCODE` = :orgId ");
                break;
            case 2://根据行医生执业点查询
                stringBuffer.append(" SELECT   p.org_code organizationId, p.org_name organizationName, p.dept_code departmentId,  p.dept_name departmentName,p.doctor_id docId,  p.doctor_code doctorId, d.prac_type doctorJob,\n" +
                        "  d.NAME doctorName,  d.INTRODUCE doctorResume,  d.SEXCODE doctorSex,  d.EXPERT doctorGoodAt,  d.doctor_title professionalCode, d.mobile telephone, d.PROFESSIONALTITLE professionalName \n" +
                        "FROM  doctor_practising p   LEFT JOIN app_doctor d     ON p.doctor_id = d.ID WHERE p.org_code = :orgId  ");
                break;
        }

        if (StringUtils.isNotEmpty(doctorListQo.getDepartmentId())) {//科室ID
            switch (doctorListQo.getQueryType()) {
                case 1:
                    stringBuffer.append(" AND t.`CODE` = :deptCode ");
                    break;
                case 2:
                    stringBuffer.append(" AND p.dept_code = :deptCode ");
                    break;
            }
        }
        if (StringUtils.isNotEmpty(doctorListQo.getDoctorId())) {//医生ID
            switch (doctorListQo.getQueryType()) {
                case 1:
                    stringBuffer.append("and d.`CODE` = :doctorId");
                    break;
                case 2:
                    stringBuffer.append("and p.doctor_code = :doctorId");
                    break;
            }
        }
        if (StringUtils.isNotEmpty(doctorListQo.getDoctorName())) {//医生姓名
            stringBuffer.append("AND (d.NAME LIKE '" + doctorListQo.getDoctorName() + "%' or d.SPELL LIKE '" + doctorListQo.getDoctorName() + "%' ) ");

        }
        if (StringUtils.isNotEmpty(doctorListQo.getTelephone())) {//医生手机
            stringBuffer.append("AND d.mobile LIKE '" + doctorListQo.getTelephone() + "%'");
        }
        return stringBuffer;
    }

    private List<DoctorListVo> mapDocToList(final List<Map> maps) {
        List<DoctorListVo> docTeamListRespList = new ArrayList<>();
        for (Map map : maps) {
            docTeamListRespList.add(ConversionUtils.convert(map, DoctorListVo.class));
        }
        return docTeamListRespList;
    }


    public List<DepartmentListVo> queryDepartmentListByDoc(DepartmentListQo request) {

        HibernateStatelessResultAction<List<DepartmentListVo>> action = new AbstractHibernateStatelessResultAction<List<DepartmentListVo>>() {
            @Override
            public void execute(StatelessSession ss) {
                String stringBuffer = "SELECT dept_code departmentId,  dept_name departmentName FROM  doctor_practising" +
                        " where org_code =:orgCode and doctor_code = :doctorCode ";
                Query sqlQuery = ss.createSQLQuery(stringBuffer);
                sqlQuery.setParameter("orgCode", request.getOrganizationId());
                sqlQuery.setParameter("doctorCode", request.getDocId());
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                setResult(mapDeptToList(dbList));
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
}
